<template>
  <div>
    <el-menu
      active-text-color="#ffd04b"
      background-color="#545c64"
      class="el-menu-vertical-demo"
      text-color="#fff"
      :default-active="activeMenu"
    >
      <template v-for="route in visibleRoutes" :key="route.path">
        <!-- 如果有多个子路由，渲染成子菜单 -->
        <el-sub-menu v-if="route.children && route.children.length > 1" :index="route.path">
          <template #title>
            <span>{{ route.meta?.title || 'Submenu' }}</span>
          </template>
          <el-menu-item
            v-for="child in route.children"
            :key="child.path"
            :index="route.path + child.path"
            @click="navigateTo(route.path + child.path)"
          >
            {{ child.meta.title }}
          </el-menu-item>
        </el-sub-menu>

        <!-- 如果只有一个子路由或无子路由，直接渲染为单个菜单项 -->
        <el-menu-item
          v-else
          :index="route.children ? route.children[0].path : route.path"
          @click="navigateTo(route.children ? route.children[0].path : route.path)"
        >
          <span>{{ route.children ? route.children[0].meta.title : route.meta.title }}</span>
        </el-menu-item>
      </template>
    </el-menu>
  </div>
</template>
<script setup>
const activeMenu = ref('')
const router = useRouter()
const routes = router.options.routes
const visibleRoutes = computed(() => {
  return routes
    .filter(route => !route.meta?.hidden)
    .map(route => {
      // 处理子路由
      if (route.children) {
        route.children = route.children.filter(child => !child.meta?.hidden)
      }
      return route
    })
})

const navigateTo = path => {
  activeMenu.value = path
  router.push(path)
}
</script>

<style lang="scss" scoped></style>
